package com.qy.util;


import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.Map.Entry;

public class WeiXinRechargeUtil {
	/** 
     * 微信支付签名算法sign 
     * @param characterEncoding 
     * @param parameters 
     * @return 
     */  
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){  
        StringBuffer sb = new StringBuffer();  
        Set<Entry<Object, Object>> es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）  
        Iterator<Entry<Object, Object>> it = es.iterator();  
        while(it.hasNext()) {  
        	 @SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry)it.next();  
            String k = (String)entry.getKey();  
            Object v = entry.getValue();  
            if(null != v && !"".equals(v)   
                    && !"sign".equals(k) && !"key".equals(k)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  
        String sign =weixinSign(sb.toString(), characterEncoding).toUpperCase();  
        return sign;  
    }  
    
    /**
	 * weixinmd5加密
	 * @param str
	 * @return
	 */
	public static String weixinSign(String param,String key){
		 String newstr = "";
		 String str = param+"&"+"key="+key;
		try {
			// 确定计算方法
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] b = md5.digest(str.getBytes("utf8"));
			int i;
			StringBuffer buf = new StringBuffer("");
	        for (int offset = 0; offset < b.length; offset++) {
	             i = b[offset];
	             if (i < 0)
	                 i += 256;
	             if (i < 16)
	                 buf.append("0");
	             buf.append(Integer.toHexString(i));
	        }
	        newstr = buf.toString().toUpperCase();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return newstr;
	}
}
